package com.artconcurrency.chapter1;

/**
 * @ClassName com.artconcurrency.chapter1
 * Description: 死锁demo
 * <p>
Found one Java-level deadlock:
=============================
"t2":
waiting to lock monitor 0x00007ffc0600e8b8 (object 0x000000076abd2538, a java.lang.String),
which is held by "t1"
"t1":
waiting to lock monitor 0x00007ffc0600fca8 (object 0x000000076abd2568, a java.lang.String),
which is held by "t2"

Java stack information for the threads listed above:
===================================================
"t2":
at com.artconcurrency.chapter1.DeadLockDemo$2.run(DeadLockDemo.java:42)
- waiting to lock <0x000000076abd2538> (a java.lang.String)
- locked <0x000000076abd2568> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)
"t1":
at com.artconcurrency.chapter1.DeadLockDemo$1.run(DeadLockDemo.java:31)
- waiting to lock <0x000000076abd2568> (a java.lang.String)
- locked <0x000000076abd2538> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)

Found 1 deadlock.


 * </p>
 * @Author tree
 * @Date 2019/5/1 10:55
 * @Version 1.0
 */
public class DeadLockDemo {
    private static String A = "A";
    private static String B = "B";
    public static void main(String[] args) {
        new DeadLockDemo().deadlock();
    }

    private void deadlock() {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (A){
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (B){
                        System.out.println("Thread 1");
                    }
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (B){
                    synchronized (A){
                        System.out.println("Thread 2");
                    }
                }
            }
        });
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        t2.start();


    }
}
